<template>
  <div class="fixed"
       v-dialogDrag>
    <div class="content el-dialog"
         style="padding:0">
      <div class="msgTop el-dialog__header">
        <span>{{contactTitle}}</span>
        <i class="el-icon-close fr"
           style="cursor:pointer;line-height:40px;font-size:13px;"
           @click="cancelTransfer"></i>
      </div>
      <el-row style='padding:20px'>
        <p class="tip_text"
           v-if="contactType=='2'">将此工单与以下工单进行合并，确认后将进入新工单创建页面，选中工单将停止流转</p>
        <p class="tip_text"
           v-else>将此工单与以下工单进行关联</p>
        <el-row style="padding-bottom:10px;">
          <el-input prefix-icon="el-icon-search"
                    size='mini'
                    clearable
                    placeholder="请输入工单编号或客户名称"
                    style="width:80%"
                    v-model="searchContent"></el-input>
          <el-button type="primary"
                     class="el-button el-button--primary el-button--medium h30Btn fr"
                     @click="searchInfoList">查询</el-button>
        </el-row>
        <el-table :data="tableData"
                  @selection-change="handleSelectionChange"
                  @select="pinSelect"
                  border
                  height="290px"
                  @select-all="getInfoSec"
                  ref="table">
          <el-table-column type="selection"
                           min-width="10%"
                           property="true">
          </el-table-column>
          <el-table-column min-width="8%"
                           property="id"
                           label="工单编号"></el-table-column>
          <el-table-column min-width="10%"
                           property="customer_name"
                           label="客户"></el-table-column>
          <el-table-column min-width="12%"
                           property="createTime"
                           label="创建时间">
            <template slot-scope="scope">
              {{timestampToTime(scope.row.createTime)}}
            </template>
          </el-table-column>
          <el-table-column min-width="10%"
                           property="createUserName"
                           label="创建人"></el-table-column>
        </el-table>
        <el-pagination background
                       class="el-pagination-style"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="currentPage1"
                       :page-sizes="[5,10, 20, 30, 40]"
                       :page-size="pageSize1"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total">
        </el-pagination>
        <el-row>
          <el-button class="el-button el-button--primary el-button--medium h30Btn fr"
                     type="primary"
                     :disabled="!multipleSelection.length>0"
                     @click="submitForm">确 定</el-button>
          <el-button class="el-button el-button--primary el-button--medium h30Btn fr"
                     type="primary"
                     @click="cancelTransfer">取 消</el-button>
        </el-row>
      </el-row>
    </div>
  </div>
</template>

<script>
import common from "@/common/common.js";
import {
  getWorkOrderList,
} from "@/api/workOrderController";
import { concatWorkOrder } from "@/api/workOrderRelation"
export default {
  props: ["contactTitle", "contactType"],
  data () {
    return {
      multipleSelectionAll: [],   // 所有选中的数据包含跨页数据
      idKey: 'id', // 标识列表数据中每一行的唯一键的名称(需要按自己的数据改一下)
      multipleSelection: [],
      total: 0,
      page: 1,
      currentPage1: this.page,
      pageSize1: 5,
      tableData: "",
      searchContent: '',
      selectAllId: [],
      lists: [],
      changeLists: [],
      origin: -1,
      pin: false,
    }
  },
  mounted () {
    this.handleSearchData()
    window.addEventListener('keydown', code => { // 这个是获取键盘按住事件
      if (code.keyCode === 16 && code.shiftKey) { // 判断是否按住shift键，是就把pin赋值为true
        this.pin = true
      }
    })
    window.addEventListener('keyup', code => { // 这个是获取键盘松开事件
      if (code.keyCode === 16) { // 判断是否松开shift键，是就把pin赋值为false
        this.pin = false
        if (this.lists.length > 2) {
          this.multipleSelection = this.lists
        } else {
          this.multipleSelection = this.changeLists
        }
        this.selectAllIdLength = this.selectAllId.length
      }
    })
  },
  destroyed () {
    window.removeEventListener('keydown', code => {
      if (code.keyCode === 16 && code.shiftKey) {
        this.pin = true
      }
    }, false)
    window.removeEventListener('keyup', code => {
      if (code.keyCode === 16) {
        this.pin = false
      }
    }, false)
  },
  methods: {
    pinSelect (item, row) {
      const data = this.tableData // 获取所有数据
      const origin = this.origin // 起点数 从-1开始
      const endIdx = row.index // 终点数
      if (this.pin && item.includes(data[origin])) { // 判断按住
        // this.$refs.multipleTable.selectClear()
        const sum = Math.abs(origin - endIdx) + 1// 这里记录终点
        const min = Math.min(origin, endIdx)// 这里记录起点
        var i = 0

        while (i < sum) {
          const index = min + i
          this.$refs.table.toggleRowSelection(data[index], true)
          i++
        }
        this.lists = this.multipleSelection
      } else {
        this.origin = row.index // 没按住记录起点或没选起点
      }
    },
    // 时间戳转换时间
    timestampToTime (timestamp) {
      return common.timestampToTime(timestamp);
    },
    cancelTransfer () {
      this.$emit('changeShow', false)
    },
    // 关联工单
    concatWorkOrder (params) {
      concatWorkOrder(params).then(res => {
        if (res.data.retCode === 200) {
          this.$message({
            type: 'success',
            message: "关联成功"
          })
          this.$emit('changeShow', false)
        }
      })
    },
    submitForm () {
      this.getAllSelectionData()
      let arrNew = []
      let _this = this
      this.multipleSelectionAll.forEach((item) => {
        arrNew.push(item.id)
      })
      if (this.contactType == "1") {  // 关联工单时
        // 关联工单的接口数据处理
        if (arrNew.length < 1) {
          this.$message({
            message: '请选择要关联的数据',
            type: "error"
          });
          return;
        }
        let params = {
          currentWorkOrderId: this.$store.state.orderDetailsId,
          concatWorkOrderIds: arrNew.join(",")
        }
        _this.concatWorkOrder(params)
      } else if (this.contactType == "2") {  // 合并工单时
        this.$store.commit('orderTitleFun', '合并')
        if (arrNew.length < 1) {
          this.$message({
            message: '请选择要合并的数据',
            type: "error"
          });
          return;
        } else {
          this.$emit("hadleFormdetails", '合并', arrNew.join(","));
          // this.$router.push({
          //   name: "createForm",
          //   params: {
          //     list: arrNew,
          //     typeData: 4
          //   }
          // });
        }
        this.$emit('changeShow', false)
      }
    },
    searchInfoList () {
      this.page = 1
      this.handleSearchData()
    },
    // 获取列表数据
    handleSearchData () {
      let params = {
        currentPage: this.page, // 当前页
        pageSize: this.pageSize1, // 每页数量
        userId: this.$store.state.userId, // 当前用户
        searchContent: '', // 输入内容
        workOrderId: this.searchContent,
        currentWorkOrderId: this.$store.state.orderDetailsId,
        customField: {}
      }
      if (this.searchContent) {
        params.customField.customer_name = this.searchContent
      }
      let _this = this
      getWorkOrderList(params).then((res) => {
        if (res.data.retCode == 200) {
          res.data.data.forEach(item => {
            Object.assign(item, item.customField)
          })
          _this.tableData = res.data.data
          _this.total = res.data.count
          _this.tableData.forEach((item, index) => {// 遍历索引,赋值给data数据
            item.index = index
          })
          setTimeout(() => {
            this.setSelectRow();
          }, 200)
        }
      })
    },
    // 设置选中的方法
    setSelectRow () {
      if (!this.multipleSelectionAll || this.multipleSelectionAll.length <= 0) {
        return;
      }
      // 标识当前行的唯一键的名称
      let idKey = this.idKey;
      let selectAllIds = [];
      this.multipleSelectionAll.forEach(row => {
        selectAllIds.push(row[idKey]);
      })
      this.$refs.table.clearSelection();
      for (var i = 0; i < this.tableData.length; i++) {
        if (selectAllIds.indexOf(this.tableData[i][idKey]) >= 0) {
          // 设置选中，记住table组件需要使用ref="table"
          this.$refs.table.toggleRowSelection(this.tableData[i], true);
        }
      }
    },
    // 记忆选择核心方法
    changePageCoreRecordData () {
      // 标识当前行的唯一键的名称
      let idKey = this.idKey;
      let that = this;
      // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
      if (this.multipleSelectionAll.length <= 0) {
        this.multipleSelectionAll = this.multipleSelection;
        return;
      }
      // 总选择里面的key集合
      let selectAllIds = [];
      this.multipleSelectionAll.forEach(row => {
        selectAllIds.push(row[idKey]);
      })
      let selectIds = []
      // 获取当前页选中的id
      this.multipleSelection.forEach(row => {
        selectIds.push(row[idKey]);
        // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
        if (selectAllIds.indexOf(row[idKey]) < 0) {
          that.multipleSelectionAll.push(row);
        }
      })
      let noSelectIds = [];
      // 得到当前页没有选中的id
      this.tableData.forEach(row => {
        if (selectIds.indexOf(row[idKey]) < 0) {
          noSelectIds.push(row[idKey]);
        }
      })
      noSelectIds.forEach(id => {
        if (selectAllIds.indexOf(id) >= 0) {
          for (let i = 0; i < that.multipleSelectionAll.length; i++) {
            if (that.multipleSelectionAll[i][idKey] == id) {
              // 如果总选择中有未被选中的，那么就删除这条
              that.multipleSelectionAll.splice(i, 1);
              break;
            }
          }
        }
      })
    },
    sendPersonFun () {
      this.sendDialogVisible = true
    },
    handleSizeChange (val) {
      this.changePageCoreRecordData();
      this.pageSize1 = val
      this.handleSearchData()
    },
    handleCurrentChange (val) {
      this.changePageCoreRecordData();
      this.page = val
      this.handleSearchData()
    },
    // 选择数据
    handleSelectionChange (val) {
      this.multipleSelection = val;
      this.changeLists = val
    },
    // 得到选中的所有数据
    getAllSelectionData () {
      // 再执行一次记忆勾选数据匹配，目的是为了在当前页操作勾选后直接获取选中数据
      this.changePageCoreRecordData();
    },
  },
}
</script>

<style scoped>
.content {
  /* width: 40%; */
  padding: 10px;
}
.el-pagination-style {
  white-space: normal;
  text-align: right;
  padding: 10px 0;
}
.tip_text {
  padding-bottom: 10px;
}
.h30Btn {
  margin: 0 10px;
}
</style>